package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DeleteUser
 */
//@WebServlet(description = "刪除使用者", urlPatterns = { "/DeleteUser" })
public class DeleteUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteUser() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userID = request.getParameter("userID");
		String strRes = ""; // 最後執行的結果回傳

		String creator = request.getParameter("loginUser"); // 創建者
		
		Connection conn = null;
		Widgets wid = new Widgets();
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			conn = wid.getConn(true);
			// 刪除人員ID所有的角色
			String strDeleteMapping_1 = "DELETE FROM tms_roleusermapping WHERE userID=?";
			ps = conn.prepareStatement(strDeleteMapping_1);
			ps.setString(1, userID);
			ps.executeUpdate();
			// 刪除人員ID所有的畫面
			String strDeleteMapping_2 = "DELETE FROM tms_authorization_body WHERE userId=?";
			ps = conn.prepareStatement(strDeleteMapping_2);
			ps.setString(1, userID);
			ps.executeUpdate();
			
			// 刪除人員ID所有的畫面
			String strDeleteSQL = "DELETE FROM tms_personnel WHERE userID=?";
			ps = conn.prepareStatement(strDeleteSQL);
			ps.setString(1, userID);
			ps.executeUpdate();
			
			wid.keepLogUser(userID, creator, 2, conn, ps);
			
			strRes = "刪除人員成功!!";

		} catch (SQLException e) {
			strRes = wid.keepErrorMes(conn, ps, e, "", true);
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				strRes = e.toString(); 
				System.out.println(strRes);
			}
		}

		response.setContentType("application/text");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(strRes);
	}

}
